package org.gxuwz.core.dao.impl;

import java.util.List;

import org.gxuwz.core.dao.IAreaDao;
import org.gxuwz.core.dao.IInstitutionDao;
import org.gxuwz.core.entity.TArea;
import org.gxuwz.core.entity.TInstitution;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("InstitutionDao")
public class InstitutionDao extends BaseDao implements IInstitutionDao{
	@Autowired
	private SessionFactory sessionFactory;
	public Session getSession() {
		Session session = sessionFactory.openSession();
		return session;
	}
	
	@Override
	public void addInstitution(TInstitution inst) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(inst);
		tx.commit();
		session.close();
	}

	@Override
	public List<TInstitution> getAll(String agencode, String agenname) {
		List<TInstitution> list = null;
		Session session = getSession();
		String hql = "select * from t_institution where 1=1";
		//String hql = "from TFamily  where 1=1";
		if(agencode!=null&&agenname!=""){
			hql += " and agencode like '%"+agencode+"%'";
		}
		if(agenname!=null&&agenname!=""){
			hql += " and agenname like '%"+agenname+"%'";
		}
		Query query = session.createSQLQuery(hql).addEntity(TInstitution.class);
		//Query query = session.createQuery(hql);
		list = query.list();
		session.close();
		return list;
	}

	@Override
	public TInstitution getByAgenName(String agenname) {
		TInstitution inst = null;
		List<TInstitution> list = null;
		Session session = getSession();
		String hql = "select * from t_institution where 1=1";
		//String hql = "from TFamily  where 1=1";
		if(agenname!=null&&agenname!=""){
			hql += " and agenname like '%"+agenname+"%'";
		}
		Query query = session.createSQLQuery(hql).addEntity(TInstitution.class);
		list = query.list();
		session.close();
		if(list.size()>=0){
			inst =list.get(0);
		}
	    return inst;
	}

	@Override
	public void update(TInstitution inst) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.update(inst);
		tx.commit();
		session.close();
	}

	@Override
	public void delete(TInstitution inst) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.delete(inst);
		tx.commit();
		session.close();
	}

}
